//
//  TWImageCacheManager.m
//  TWHomework-WeChat
//
//  Created by wzb on 2019/11/13.
//  Copyright © 2019 WZB. All rights reserved.
//

#import "TWImageCacheManager.h"
#import <CommonCrypto/CommonDigest.h>
#import "TWWebClient.h"

@interface TWImageCacheManager ()

/// 内存缓存图片引用
@property (nonatomic, strong) NSMutableDictionary *memCache;

/// 物理缓存路径
@property (nonatomic, strong) NSString *diskCachePath;

/// 存储图片下载状态 key: 图片md5，value：0未下载，1正在下载，2下载成功
@property (nonatomic, strong) NSMutableDictionary *imageDownloadStatusCache;

@end

@implementation TWImageCacheManager

#pragma mark - lazy
- (NSMutableDictionary *)imageDownloadStatusCache
{
    if (!_imageDownloadStatusCache) {
        _imageDownloadStatusCache = [NSMutableDictionary dictionary];
    }
    return _imageDownloadStatusCache;
}

- (instancetype)init
{
    if ((self = [super init]))
    {
        // Init the memory cache
        self.memCache = [[NSMutableDictionary alloc] init];
          
        // Init the disk cache
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        self.diskCachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"ImageCache"];
          
        if (![[NSFileManager defaultManager] fileExistsAtPath:self.diskCachePath])
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:self.diskCachePath
                                      withIntermediateDirectories:YES
                                                       attributes:nil
                                                            error:NULL];
        }
    }
    return self;
}

// 保存图片
- (void)storeImageForURL:(NSString *)URL image:(UIImage *)image imageData:(NSData *)imageData
{
    NSString *key = [self cachePathForKey:URL];
    [self.memCache setValue:image forKey:key];

    NSFileManager *fileManager = [[NSFileManager alloc] init];
    // 如果有数据，则保存到物理存储上
    if (imageData) {
        [fileManager createFileAtPath:key contents:imageData attributes:nil];
    } else {
        if (image)
        {
            [fileManager createFileAtPath:key contents:UIImageJPEGRepresentation(image, (CGFloat)1.0) attributes:nil];
        }
    }
}

// 通过key返回UIImage
- (void)imageFromURL:(NSString *)URL success:(void(^)(UIImage *image))success
{
    NSString *key = [self cachePathForKey:URL];
    __block UIImage *resultImage = [self.memCache valueForKey:key];
    if (resultImage) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success) {
                success(resultImage);
            }
        });
        return ;
    }

    resultImage = [[UIImage alloc] initWithContentsOfFile:key];
    if (resultImage)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success) {
                success(resultImage);
            }
        });
        [self.memCache setValue:resultImage forKey:key];
        return ;
    }
    NSInteger imageDownloadStatus = [[self.imageDownloadStatusCache valueForKey:key] intValue];
    if (imageDownloadStatus == 1) {
        // 避免重复下载
        return;
    }
    [self.imageDownloadStatusCache setValue:@(1) forKey:key];
    [[TWWebClient sharedClient] downloadImage:URL success:^(UIImage * _Nonnull image) {
        [self.imageDownloadStatusCache setValue:@(2) forKey:key];
        resultImage = image;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success) {
                success(resultImage);
            }
        });
        [self storeImageForURL:URL image:resultImage imageData:nil];
    } failure:^(NSError * _Nonnull error) {
        [self.imageDownloadStatusCache setValue:@(0) forKey:key];
        #warning TODO 错误处理
    }];
//    [self.downloadQueue addOperation:[NSBlockOperation blockOperationWithBlock:^{
//        NSError *error;
//        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:URL] options:NSDataReadingMappedIfSafe error:&error];
//        if (error) {
//            NSLog(@"download error----url:%@\n---error:%@", URL, error);
//        }
//        resultImage = [UIImage imageWithData:data];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (success) {
//                success(resultImage);
//            }
//        });
//    }]];
}

+ (instancetype)sharedManager
{
    static TWImageCacheManager *_manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[self alloc] init];
    });
    return _manager;
}
  
/*
 *创建指定图片key的路径
 */
- (NSString *)cachePathForKey:(NSString *)key
{
    const char *str = [key UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
      
    return [self.diskCachePath stringByAppendingPathComponent:filename];
}

@end
